<template>
    <div class="main_body">
        <header >
            <a @click="$api.goBack()" class="back"></a>
            <span v-if="classId">班级详情</span>
            <span v-if="!classId">添加班级</span>
            <a @click="addClass()" class="add">完成</a>
        </header>
        <div class="select_class">
                <div class="model" @click="$api.clickModel(1)" v-if="!useInfo.tsMenuList[1].voOperate.editObj" ></div>
            <div class="main"  @click="changePhoto()">
                <div class="flex">
                    <div>班级图标</div>
                    <div class="red">*</div>
                </div>
                <div @click.stop="$api.showImgDetail(detail.classPhoto)"><img class="image_wrap" :src="$api.formatterImg(detail.classPhoto)"/></div>
            </div>
            <div class="main">
                <div class="flex">
                    <div>班级类型</div>
                    <div class="red">*</div>
                </div>
                <div @click="openClassPicker" v-if="detail.classType">培训班</div>
                <div @click="openClassPicker" v-if="!detail.classType">托管班</div>
            </div>
            <div class="main">
                <div class="flex">
                    <div>班级名称</div>
                    <div class="red">*</div>
                </div>
                <div><input :disabled="detail.classId" @change='changeClassName' v-model="detail.className"/></div>
            </div>
            <div class="main" @click="openTimePicker()">
                <div class="flex">
                    <div>起始日期</div>
                    <div class="red">*</div>
                </div>
                <div>{{new Date(detail.startTime).Format("yyyy-MM-dd")}}</div>
            </div>
            <div class="main" @click="openTimePicker(1)">
                <div class="flex">
                    <div>结束日期</div>
                    <div class="red">*</div>
                </div>
                <div >{{new Date(detail.endTime).Format("yyyy-MM-dd")}}</div>
            </div>
            <div class="main" @click="openYearPicker()">
                <div class="flex">
                    <div>学期</div>
                    <div class="red">*</div>
                </div>
                <div class="flex" ><div class="desc1">{{xueqi1}}</div><div class="more"></div></div>
            </div>
            <div class="main" @click="selectMainTeacher" >
                <div class="flex">
                    <div>主教教师</div>
                    <div class="red">*</div>
                </div>
                <div class="flex"><div class="desc1">{{detail.mainTeacherName}}</div><div class="more"></div></div>
            </div>
            <div class="main" @click="selectAideTeacher" >
                <div class="flex">
                    <div>助教教师</div>
                </div>
                <div class="flex"><div class="desc1">{{detail.aideTeacherName}}</div><div class="more"></div></div>
            </div>
            <div class="main" @click="selectService">
                <div class="flex">
                    <div>服务</div>
                    <div class="red">*</div>
                </div>
                <div class="flex"><div class="desc1">{{detail.patternName}}</div><div class="more"></div></div>
            </div>
            <!-- <div class="main">
                <div class="flex">
                    <div>缴费模式</div>
                    <div class="red">*</div>
                </div>
                <div class="flex"><div class="desc1">{{formatPayPattern(detail.payPattern)}}</div><div class="more"></div></div>
            </div> -->
            <div class="main">
                <div class="flex">
                    <div>学费</div>
                </div>
                <div><div class="flex"><div >{{detail.schoolFee}}{{formaterParttern(detail.payPattern)}}</div></div></div>
            </div> 
            <div class="row" v-if="detail.classId" @click="showClassStudent" style="padding:0.37333rem;">
                <mt-button style="width:100%;" type="primary">查看学生</mt-button>
            </div>
            <div class="row" v-if="detail.classId&&useInfo.tsMenuList[1].voOperate.removeObj" @click="deleteClass" style="padding:0 0.37333rem">
                <mt-button style="width:100%;" type="danger">删除</mt-button>
            </div> 
            <div class="row" v-if="!detail.classId" @click="addClass" style="padding:0.37333rem;">
                <mt-button style="width:100%;" type="primary">完成</mt-button>
            </div>
            <!-- <div class="row" v-if="!detail.classId" @click="addStudent" style="padding:0 0.37333rem">
                <mt-button style="width:100%;" type="danger">继续加入学生</mt-button>
            </div>           -->
            <mt-datetime-picker v-model='startTime' ref="beginDate" type="date"  @confirm="changeStartTime" >
            </mt-datetime-picker>
            <mt-datetime-picker v-model='endTime' ref="endDate" type="date" @confirm="changeEndTime" >
            </mt-datetime-picker>
            <!-- 选择学期弹窗 -->
            <mt-popup style="background:white;width:100%;"
            v-model="popupYear"
            position="bottom">
            <div class="picker-toolbar" style="border-bottom:1px solid #f2f2f2">
                <span @click="SureOrCanelChangeYear(1)" class="mint-datetime-action mint-datetime-cancel">取消</span> 
                <span @click="SureOrCanelChangeYear()" class="mint-datetime-action mint-datetime-confirm">确定</span>
            </div>
            <mt-picker :slots="slots"  @change="ChangeYear"></mt-picker>
            </mt-popup>
        <!-- 选择班级类型弹窗 -->
            <mt-popup style="background:white;width:100%;"
            v-model="popupClass"
            position="bottom">
            <div class="picker-toolbar" style="border-bottom:1px solid #f2f2f2">
                <span @click="SureOrCanelChangeClass(1)" class="mint-datetime-action mint-datetime-cancel">取消</span> 
                <span @click="SureOrCanelChangeClass()" class="mint-datetime-action mint-datetime-confirm">确定</span>
            </div>
            <mt-picker :slots="slots2"  @change="ChangeClass"></mt-picker>
            </mt-popup>
        </div>

        <getImage v-model='sheetVisible' ></getImage>
    </div>
</template>

<script>
    import {
        MessageBox
    } from 'mint-ui';
    import getImage from '../components/getImage.vue'
    export default {
        data() {
            return {
                slots: this.getXueQiList(),
                slots2: [{
                    values: ['托管班', '培训班'],
                    className: 'slot2',
                    textAlign: 'center'
                }],
                type: false, //判断新增或者编辑
                content: '',
                popupYear: false,
                popupClass: false,
                sheetVisible: false,
                useInfo: '',
                classId: null,
                xueqi: '', //缓存学期
                class: '', //缓存的班级
                xueqi1: '', //展示的学期
                startTime: new Date(), //过度时间
                endTime: new Date(), //过度时间
                detail: {
                    first: 1,
                    classPhoto: null,
                    classType: 0,
                    startTime: new Date(),
                    endTime: new Date(),
                    className: '',
                    content: ''
                },
            }
        },
        components: {
            getImage
        },
        methods: { // 
            formaterParttern(type) {
                if (!type) {
                    return '元/次'
                }
                switch (type) {
                    case 1:
                        return '元/期';
                        break;
                    case 2:
                        return '元/月';
                        break;
                    case 3:
                        return '元/次';
                        break;
                }
            },
            getXueQiList() { //获取选择学期的数组
                var year = new Date().Format('yyyy');
                var upYear = parseInt(year) - 5;
                var downYear = parseInt(year) + 5;
                var values = [];
                for (var i = upYear; i <= downYear; i++) {
                    values.push(i + '-上');
                    values.push(i + '-下');
                }
                return [{
                    flex: 1,
                    values,
                    defaultIndex: 10,
                    className: 'slot1',
                    textAlign: 'center'
                }];
            },
            selectMainTeacher() { //选择主要教师
                var teacherOption = {
                    title: 'selectMainTeacher',
                    teacherIds: this.detail.aideTeacherId,
                }
                sessionStorage.setItem('teacherOption', JSON.stringify(teacherOption))

                this.$router.push({
                    path: 'selectTeacher',
                });
            },
            showClassStudent() { //查看学生
                sessionStorage.setItem('studentListType', '3');
                this.$api.removeCookie("studentDetail");
                this.$router.push({
                    path: 'qiandaolist'
                })
            },
            selectService() { //选择服务
                var teacherOption = {
                    title: 'selectService',
                    teacherIds: this.detail.servicePatternId
                }
                sessionStorage.setItem('teacherOption', JSON.stringify(teacherOption))
                this.$router.push({
                    path: 'selectService',
                });
            },
            changeStartTime() { //改变开始时间
                if (this.startTime > this.detail.endTime) {
                    MessageBox('提示', '结束时间需要大于开始时间!')
                    return;
                }
                this.detail.startTime = this.startTime;
                this.beginAddOrEdit();
            },
            changeEndTime() { //改变开始时间
                if (this.detail.startTime > this.endTime) {
                    MessageBox('提示', '结束时间需要大于开始时间!')
                    return;
                }
                this.detail.endTime = this.endTime;

                this.beginAddOrEdit();
            },
            selectAideTeacher() { //选择助教老师
                var teacherOption = {
                    title: 'selectAideTeacher',
                    teacherIds: this.detail.aideTeacherId,
                }
                sessionStorage.setItem('teacherOption', JSON.stringify(teacherOption))
                this.$router.push({
                    path: 'selectTeacher',
                });
            },
            changeClassName(e, value) {
                this.beginAddOrEdit();
            },
            getRadioBack() { //获取选择的老师
                var teacher = JSON.parse(sessionStorage.getItem('radioBackOptions'));
                console.log(JSON.parse(sessionStorage.getItem('radioBackOptions')));
                if (teacher) {
                    switch (teacher.title) {
                        case 'selectMainTeacher':
                            this.detail.mainTeacherId = teacher.item.teacherId
                            this.detail.mainTeacherName = teacher.item.teacherName
                            break;
                        case 'selectAideTeacher':
                            this.detail.aideTeacherId = teacher.item.teacherId
                            this.detail.aideTeacherName = teacher.item.teacherName
                            break;
                        case 'selectService':
                            this.detail.servicePatternId = teacher.item.servicePatternId
                            this.detail.patternName = teacher.item.patternName
                            this.detail.schoolFee = teacher.item.patternPrice
                            break;
                    }

                    this.beginAddOrEdit();
                    sessionStorage.removeItem('radioBackOptions');
                }
            },
            deleteClass() { //删除班级
                var url = "/class/remove";
                var params = {
                    classId: this.detail.classId
                };
                MessageBox.confirm('确定要删除班级?').then(action => {
                    this.$api.post(url, params, (data) => {
                        MessageBox('提示', '删除成功');
                        sessionStorage.removeItem('radioBackOptions');
                        this.$api.goBack();
                    })
                }).catch(e => {

                });

            },
            addClass() { //校验参数,确认无误执行 addOrEditClass
                console.log(JSON.parse(JSON.stringify(this.detail)));
                if (!this.detail.classPhoto) { //如果没有图标
                    MessageBox('提示', '请选择图标');
                    return false;
                }
                if (!this.detail.className.trim().length > 0) { //如果没有班级名称
                    MessageBox('提示', '请输入班级名称');
                    return false;
                }
                if (!this.detail.studyYear) { //如果没有选择学期
                    MessageBox('提示', '请选择学期');
                    return false;
                }
                if (!this.detail.mainTeacherId) { //如果没有主教教师
                    MessageBox('提示', '请选择主教教师');
                    return false;
                }
                if (!this.detail.servicePatternId) { //如果没有服务
                    MessageBox('提示', '请选择服务');
                    return false;
                }
                this.addOrEditClass();
            },
            addStudent() { //继续加入学生
                var studentType = {
                    header: '加入学生',
                    type: 1,
                }
                sessionStorage.setItem('studentType', JSON.stringify(studentType));
                this.$router.push({
                    path: 'g14',
                });
            },
            beginAddOrEdit() { //新增或编辑之前,用于做各种判断
                sessionStorage.setItem('detail', JSON.stringify(this.detail));
                // console.log(this.detail.classId);
                // if (this.detail.classId) { //有classId说明是编辑,直接进入编辑
                //     // console.log(typeof(this.detail.startTime));
                //     // console.log(typeof(this.detail.endTime));
                //     // return;


                // } else {
                //     sessionStorage.setItem('detail', JSON.stringify(this.detail));
                // }
            },
            addOrEditClass() { //新增或者编辑班级
                var params = this.detail
                params.schoolId = this.useInfo.schoolId
                var url = "/class/save"
                console.log(1234);
                if (!params.classId) { //新增班级特殊处理
                    var selectStudentList = JSON.parse(sessionStorage.getItem('selectStudentList'));
                    if (selectStudentList) {
                        var str = '';
                        selectStudentList.forEach(element => {
                            str = str + element.studentId + ','
                        });
                        params.studentIds = str;
                    }
                }
                this.$api.post(url, params, (data) => {
                    if (!params.classId) { //如果是新增班级
                        console.log(data.info)
                        var that = this;
                        MessageBox.confirm('新增班级成功,是否立即添加学生?').then(action => {
                            sessionStorage.setItem('classId', data.info)
                            that.$api.clearItem('classId');
                            that.showClassStudent();
                        }).catch(e => {
                            that.$api.clearItem();
                            that.$api.goBack();
                        })

                    } else {
                        MessageBox('提示', '修改成功')
                        this.$api.clearItem('classId');
                    }
                })
            },
            openTimePicker(end) { //打开时间选择器
                if (end) {
                    this.$refs.endDate.open();
                } else {
                    this.$refs.beginDate.open();
                }
            },
            openYearPicker() {
                this.popupYear = true;
            },
            openClassPicker() {
                this.popupClass = true;
            },
            SureOrCanelChangeYear(cancel) { //学期选择器 确定取消点击事件
                if (!cancel) {
                    this.xueqi1 = this.xueqi;
                    var year = this.xueqi1.split('-')[0];
                    var xueqi = this.xueqi1.split('-')[1];
                    this.detail.studyYear = year;
                    if (xueqi == '上') {
                        this.detail.studyTerm = 0;
                    } else {
                        this.detail.studyTerm = 1;
                    }
                    this.beginAddOrEdit();
                }
                this.popupYear = false;
            },
            SureOrCanelChangeClass(cancel) { //班级类型选择器 确定取消点击事件
                if (!cancel) {
                    console.log(this.class);
                    switch (this.class) {
                        case '托管班':
                            this.detail.classType = 0;
                            break;
                        default:
                            this.detail.classType = 1;
                            break;
                    }
                    this.beginAddOrEdit();
                }
                this.popupClass = false;
            },
            ChangeYear(picker, values) { //选择学期
                this.xueqi = values[0];
            },
            ChangeClass(picker, values) { //选择班级
                this.class = values[0];
            },
            changePhoto() {
                this.sheetVisible = true;
            },
            getUseInfo() {
                this.useInfo = JSON.parse(sessionStorage.getItem('useInfo'));
            },
            getDetail() {
                this.classId = JSON.parse(sessionStorage.getItem('classId'));
                let detail = JSON.parse(sessionStorage.getItem('detail'));
                if (detail) { //有缓存数据直接用缓存数据
                    this.detail = detail
                    if (this.detail.studyYear) {
                        if (this.detail.studyTerm) { //如果是下学期
                            this.xueqi1 = this.detail.studyYear + '-下'
                        } else {
                            this.xueqi1 = this.detail.studyYear + '-上'
                        }
                    }
                    this.getRadioBack();
                    this.getImageBack();
                    return;
                } else if (this.classId) { //如果是从班级列表点进来
                    var url = "/class/find"
                    var params = {
                        classId: this.classId,
                        schoolId: this.useInfo.schoolId
                    }
                    this.$api.post(url, params, (data) => {
                        console.log(JSON.parse(JSON.stringify(data)))
                        this.detail = data.info.tsClass

                        this.startTime = this.detail.startTime = new Date(this.detail.startTime);
                        this.endTime = this.detail.endTime = new Date(this.detail.endTime);
                        if (this.detail.studyTerm) { //如果是下学期
                            this.xueqi1 = this.detail.studyYear + '-下'
                        } else {
                            this.xueqi1 = this.detail.studyYear + '-上'
                        }

                        console.log(213412);
                        // console.log(JSON.parse(JSON.stringify(data.info)));
                        this.getImageBack();
                        this.getRadioBack();
                    })
                } else {
                    this.getImageBack();
                    this.getRadioBack();
                }

            },
            getImageBack() { //
                var filepath = JSON.parse(sessionStorage.getItem('imgOption'));
                if (filepath) {
                    this.detail.classPhoto = filepath.filePath;
                    this.detail.baseFileId = filepath.baseFileId;
                    this.beginAddOrEdit();
                }

            },
            formatPayPattern(type) { //格式化缴费模式
                if (type == 1) {
                    return '按期缴费';
                } else if (type == 2) {
                    return '按月缴费';
                }
            }
        },
        // watch: {
        //     detail(newValue, oldValue) {
        //         console.log(123);
        //         this.addOrEditClass();
        //     }
        // },
        created() {
            this.getUseInfo();
            this.getDetail();
        },

    }
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
    .main_body {
        background: white;
        height: 100%;
    }
</style>